package com.sousb;


import java.util.ArrayList;
import java.util.List;

import org.achartengine.GraphicalView;
import org.achartengine.chart.AbstractChart;
import org.achartengine.chart.LineChart;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint.Align;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Scroller;

/**
 * 
 * @author 
 * @createDate 
 * @version v0.5.1
 */

public class FlipPageWidget extends ViewGroup {
	
	boolean  dzyFlipNext= false;
	boolean  dzyFlipPre= false;

	public static final int FLIP_DIRECTION_PRE = 1;
	public static final int FLIP_DIRECTION_NEXT = 2;

	private boolean isFlipPre = true;
	private boolean isFlipNext = true;

	private static final int INVALID_SCREEN = -1;
	private int mDefaultScreen;
	private boolean mFirstLayout = true;
	private int mCurrentScreen;
	private int mNextScreen = INVALID_SCREEN;

	private Scroller mScroller;

	private float mLastMotionX;
	private float mLastMotionY;
	
	
	private final static int TOUCH_STATE_REST = 0;
	

	private final static int TOUCH_STATE_SCROLLING = 1;
	
	private int mTouchState = TOUCH_STATE_REST;
	
	public static int mDefaultSlop;
	

	public static int mTouchSlop; 

	
	private int mDataIndex = 100; 
	
	private int mNextDataIndex = INVALID_SCREEN;
	
	private IFlipWidgetListener mListener;
	
	private boolean isAddFinish = false;
	
	private boolean isChangeScreen = false;

	/**
	 * Used to inflate the Workspace from XML.
	 */
	private Context context;
	
	
	LinearLayout page2;
	
	public FlipPageWidget(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	/**
	 * Used to inflate the Workspace from XML.
	 */
	public FlipPageWidget(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		
		this.context = context;
		
		mDefaultScreen = 1;
		initView();
	}
	
	public void updatePage2(){
		
		if(page2==null)
			return;
		
		page2.removeAllViews();
		
		AbstractChart mChart = new LineChart(BusData.getInstance().getDataSet(),
				BusData.getInstance().getChartRender());
		GraphicalView mView = new GraphicalView(context, mChart);

		page2.addView(mView);
	}

	public void initView() {
		mScroller = new Scroller(getContext());
		mCurrentScreen = mDefaultScreen;

		final ViewConfiguration configuration = ViewConfiguration
				.get(getContext());
		mDefaultSlop = configuration.getScaledTouchSlop();
		mTouchSlop = mDefaultSlop;

		/*
		 * 
		 * 
		 * */
		LayoutInflater inflater = LayoutInflater.from(getContext());
		/*for (int i = 0; i < 3; i++) {
			View view = inflater.inflate(R.layout.sub_page, null, false);
			addView(view);
			Log.i("dzy", view.toString());
		}*/
		View view = inflater.inflate(R.layout.sub_page3, null, false);
		addView(view);
		
		view = inflater.inflate(R.layout.sub_page1, null, false);
		addView(view);
		
		
		page2 = (LinearLayout)inflater.inflate(R.layout.sub_page2, null, false);
		
		/////////////////////////////////////////////////////////////////////////
		

		
		AbstractChart mChart = new LineChart(BusData.getInstance().getDataSet(),
												BusData.getInstance().getChartRender());
		GraphicalView mView = new GraphicalView(context, mChart);
		
		page2.addView(mView);
		
		
		/////////////////////////////////////////////////////////////////////////
		
		addView(page2);
		
		
		setViewId();
	}

	@Override
	public void computeScroll() {
		if (mScroller.computeScrollOffset()) {
			if ((isAddFinish)
					&& (mScroller.getCurrX() == (mScroller.getFinalX()))) {
				if (mNextDataIndex > mDataIndex) {
					scrollToNext(mNextDataIndex);
				} else if (mNextDataIndex < mDataIndex) {
					scrollToPrev(mNextDataIndex);
				}
				if (isChangeScreen) {
					if (mListener != null) {
						mListener.onFlipCompleted();
					}
					if (mNextScreen != INVALID_SCREEN) {
						mCurrentScreen = Math.max(0,
								Math.min(mNextScreen, getChildCount() - 1));
						mNextScreen = INVALID_SCREEN;
					}
				}
				isAddFinish = false;
			}
			scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
			postInvalidate();
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * 
	 */
	@Override
	public void dispatchDraw(Canvas canvas) {
		boolean restore = false;
		boolean fastDraw = mTouchState != TOUCH_STATE_SCROLLING
				&& mNextScreen == INVALID_SCREEN;
		// If we are not scrolling or flinging, draw only the current screen
		if (fastDraw) {
			//Log.i("dzy","fastDraw");always run here
			final int count = getChildCount();
			for (int i = 0; i < count; i++) {
				drawChild(canvas, getChildAt(i), getDrawingTime());
			}
		} else {
			
			//Log.i("dzy","fastDraw else");
			final long drawingTime = getDrawingTime();
			// If we are flinging, draw only the current screen and the target
			// screen
			if (mNextScreen >= 0 && mNextScreen < getChildCount()
					&& Math.abs(mCurrentScreen - mNextScreen) == 1) {
				drawChild(canvas, getChildAt(mCurrentScreen), drawingTime);
				drawChild(canvas, getChildAt(mNextScreen), drawingTime);
			} else {
				// If we are scrolling, draw all of our children
				final int count = getChildCount();
				for (int i = 0; i < count; i++) {
					drawChild(canvas, getChildAt(i), drawingTime);
				}
			}
		}
		if (restore) {
			canvas.restore();
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.View#onMeasure(int, int)
	 * 
	 */
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);

		final int width = MeasureSpec.getSize(widthMeasureSpec);
		final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
		
		if (widthMode != MeasureSpec.EXACTLY) {
			throw new IllegalStateException(
					"Workspace can only be used in EXACTLY mode.");
		}

		final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
		if (heightMode != MeasureSpec.EXACTLY) {
			throw new IllegalStateException(
					"Workspace can only be used in EXACTLY mode.");
		}

		// The children are given the same width and height as the workspace
		final int count = getChildCount();
		for (int i = 0; i < count; i++) {
			getChildAt(i).measure(widthMeasureSpec, heightMeasureSpec);
		}

		if (mFirstLayout) {
			scrollTo(mCurrentScreen * width, 0);
			mFirstLayout = false;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.ViewGroup#onLayout(boolean, int, int, int, int)
	 * 
	 */
	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) {
		int childLeft = 0;
		int tempWidth = 0;
		
		for (int i = 0; i < getChildCount(); i++) {
			final View child = getChildAt(i);
			if (child.getVisibility() != View.GONE) {
				final int childWidth = child.getMeasuredWidth();
				tempWidth = childWidth;
				childLeft = (mDataIndex + i - 1) * childWidth;
				child.layout(childLeft, 0, childLeft + childWidth,
						child.getMeasuredHeight());
			}
		}
		snapToScreen(mDataIndex, tempWidth);
	}

	@Override
	public boolean dispatchUnhandledMove(View focused, int direction) {
		if (direction == View.FOCUS_LEFT) {
			if (getCurrentScreen() > 0) {
				snapToScreen(getCurrentScreen() - 1);
				return true;
			}
		} else if (direction == View.FOCUS_RIGHT) {
			if (getCurrentScreen() < getChildCount() - 1) {
				snapToScreen(getCurrentScreen() + 1);
				return true;
			}
		}
		return super.dispatchUnhandledMove(focused, direction);
	}

	private int getCurrentScreen() {
		for (int i = 0; i < getChildCount(); i++) {
			if (getChildAt(i).getId() == mDataIndex) {
				return i;
			}
		}
		return mCurrentScreen;
	}

	private int getNextScreen(int dataIndex) {
		for (int i = 0; i < getChildCount(); i++) {
			if (getChildAt(i).getId() == dataIndex) {
				return i;
			}
		}
		return mNextScreen;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * android.view.ViewGroup#onInterceptTouchEvent(android.view.MotionEvent)
	 *
	 */
	@Override
	public boolean onInterceptTouchEvent(MotionEvent ev) {
		final int action = ev.getAction();
		Log.i("dzy","onInterceptTouchEvent():mTouchState="+mTouchState);
		if ((action == MotionEvent.ACTION_MOVE)
				&& (mTouchState != TOUCH_STATE_REST)) {
			Log.i("dzy",mTouchState+"");
			return true;
		}
		
		final float x = ev.getX();
		final float y = ev.getY();

		switch (action) {
		case MotionEvent.ACTION_MOVE:
			/*
			 * 鐠佹澘缍峹y娑撳窇LastMotionX閵嗕沟LastMotionY瀹割喖锟斤拷鑲╂畱缂佹繂顕崐绗猴拷锟藉�Diff閸滃瘔Diff婢堆傜艾
			 * touchSlop閺冭泛姘ㄧ拋銈勮礋閻ｅ矂娼伴幏鏍уЗ娴滃棜鍐绘径鐔枫亣閻ㄥ嫯绐涚粋浼欑礉鐏炲繐绠风亸鍗炲讲娴犮儳些閸斻劋绨￠妴锟斤拷
			 */
			Log.i("dzy","onInterceptTouchEvent():ACTION_MOVE");
			final int xDiff = (int) Math.abs(x - mLastMotionX);
			final int yDiff = (int) Math.abs(y - mLastMotionY);
			final int touchSlop = mTouchSlop;
			boolean xMoved = (xDiff > touchSlop) && (xDiff >= 2 * yDiff);
			boolean yMoved = yDiff > touchSlop;
			Log.i("dzy","xMoved="+xMoved+",yMoved="+yMoved);
			if (xMoved || yMoved) {
				if (xMoved) {
					// Scroll if the user moved far enough along the X axis
					mTouchState = TOUCH_STATE_SCROLLING;
				}
			}
			break;
		case MotionEvent.ACTION_DOWN:
			// Remember location of down touch
			Log.i("dzy","onInterceptTouchEvent():ACTION_DOWN");
			mLastMotionX = x;
			mLastMotionY = y;
			Log.i("dzy", ""+mScroller.isFinished());
			mTouchState = mScroller.isFinished() ? TOUCH_STATE_REST
					: TOUCH_STATE_SCROLLING;
			break;
		case MotionEvent.ACTION_CANCEL:
		case MotionEvent.ACTION_UP:
			// Release the drag
			mTouchState = TOUCH_STATE_REST;
			break;
		}
		Log.i("dzy", "return="+mTouchState);
		return mTouchState != TOUCH_STATE_REST;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * onInterceptTouchEvent()杩斿洖true,鍚庤繘鍏nTouchEvent()
	 * 
	 * @see android.view.View#onTouchEvent(android.view.MotionEvent)
	 * 
	 */
	@Override
	public boolean onTouchEvent(MotionEvent ev) {
		
		final int action = ev.getAction();
		final float x = ev.getX();
		//Log.i("dzy", "x="+x);
		//Log.i("dzy",mTouchState+"");
		switch (action) {
		
		case MotionEvent.ACTION_DOWN:
			Log.i("dzy", "ACTION DOWN");
			if (!mScroller.isFinished()) {
				
				mScroller.abortAnimation();
			}
			// Remember where the motion event started
			mLastMotionX = x;
			break;
			
		case MotionEvent.ACTION_MOVE:
			
			Log.i("dzy", "ACTION_MOVE");
			// onInterceptTouchEvent()閫氳繃娴嬭瘯锛屼細鏀规垚TOUCH_STATE_SCROLLING鐘舵�
			if ((mTouchState == TOUCH_STATE_SCROLLING) && ((!isAddFinish))) {
				// Scroll to follow the motion event
				final int deltaX = (int) (mLastMotionX - x);
				mLastMotionX = x;
				if (deltaX < 0) {
					if ((isFlipPre) && (getScrollX() > 0)) {
						
						//鏀瑰彉婊氬姩鏉＄殑浣嶇疆锛岀浉褰撲簬宸︽粴
						scrollBy(Math.max(-1 * getScrollX(), deltaX), 0);
					}
				} else if (deltaX > 0) {
					
					
					final int availableToScroll = getChildAt(
							getChildCount() - 1).getRight()
							- getScrollX() - getWidth();
					Log.i("dzy", availableToScroll+"Move");
					if ((availableToScroll > 0) && (isFlipNext)) {
						
						
						scrollBy(Math.min(availableToScroll, deltaX), 0);
					}
				}
			}
			break;
		case MotionEvent.ACTION_UP:
			Log.i("dzy", x+"ACTION_UP");
			
			if (mTouchState == TOUCH_STATE_SCROLLING) {
				snapToDestination();
				
			}
			
			mTouchState = TOUCH_STATE_REST;
			break;
		case MotionEvent.ACTION_CANCEL:
			mTouchState = TOUCH_STATE_REST;
			break;
		default:
			break;
		}
		return true;
	}

	private void snapToDestination() {
		if (mListener != null) {
			mListener.onFlipStarted();
		}

		final int screenWidth = getWidth();
		final int whichScreen = (getScrollX() + (screenWidth / 2))
				/ screenWidth;
		
		Log.v("dzy","snapToDestination():getScrollX()="+getScrollX());
		Log.v("dzy","snapToDestination():screenWidth="+screenWidth);
		Log.v("dzy","snapToDestination():whichScreen="+whichScreen);
		snapToScreen(whichScreen);
	}

	void snapToScreen(int dataIndex) {
		if (!mScroller.isFinished())
			return;
		isAddFinish = true;
		mNextDataIndex = dataIndex;

		Log.v("dzy","snapToScreen():dataIndex="+dataIndex);
		
		boolean changingScreens = dataIndex != mDataIndex;
		View focusedChild = getFocusedChild();
		if (focusedChild != null && changingScreens) {
			focusedChild.clearFocus();
		}
		final int cx = getScrollX();  
		final int newX = dataIndex * getWidth();  
		final int delta = newX - cx; 
		
		if(delta>0){
			dzyFlipNext = true;
			dzyFlipPre = false;
		}
		else if(delta<0){ 
			dzyFlipPre = true;
			dzyFlipNext = false;
		}
		
		Log.i("dzysnapToScreen", "Scroll from:"+cx+",to:"+(cx+delta));
		
		mScroller.startScroll(cx, 0, delta, 0, Math.abs(delta) * 2);
		
		invalidate();
	}

	private void snapToScreen(int dataIndex, int width) {

		
		if (getFocusedChild() != null && dataIndex != this.mDataIndex) {
			getFocusedChild().clearFocus();
		}
		final int delta = dataIndex * width - getScrollX();
		
		//add by dzy,resolve a bug
		if(delta<0&&dzyFlipNext)
			return;
		if(delta>0&&dzyFlipPre)
			return;
		
		Log.i("(layout)dzy", "Scroll from:"+getScrollX()+",to:"+(getScrollX()+delta));
									
		
		mScroller.startScroll(getScrollX(), 0, delta, 0, 500);
			
		invalidate();
	}

	private void scrollToNext(int dataIndex) {
		if (!isFlipPre){
			//isFlipNext = false;
			isFlipPre = true;
		}

		isChangeScreen = true;
		mNextScreen = getNextScreen(dataIndex);
		mCurrentScreen = getCurrentScreen();
		mDataIndex = dataIndex;

		if (isFlipNext) {
			View view = getChildAt(0);
			removeViewAt(0);
			addView(view, 2);
			setViewId();
			invalidate();
			// try {
			// Thread.currentThread();
			// Thread.sleep(1000);
			// } catch (InterruptedException ex) {
			// ex.printStackTrace();
			// }
		}
	}

	private void scrollToPrev(int dataIndex) {
		if (!isFlipNext){
			isFlipNext = true;
			//isFlipPre = false;
		}

		isChangeScreen = true;
		mNextScreen = getNextScreen(dataIndex);
		mCurrentScreen = getCurrentScreen();
		mDataIndex = dataIndex;

		if (isFlipPre) {
			View view = getChildAt(2);
			removeViewAt(2);
			addView(view, 0);
			setViewId();
			invalidate();
			
		}
	}

	private void setViewId() {
		
		//Log.i("dzy", "setViewId():mDataIndex=" + mDataIndex);
		getChildAt(0).setId(mDataIndex - 1);
		getChildAt(1).setId(mDataIndex);
		getChildAt(2).setId(mDataIndex + 1);
	}

	public void addListener(IFlipWidgetListener listener) {
		this.mListener = listener;
	}

	public View getCurrentView() {
		if (mDataIndex == -1)
			return getChildAt(mDefaultScreen);

		for (int i = 0; i < getChildCount(); i++) {
			if (getChildAt(i).getId() == (mDataIndex)) {
				return getChildAt(i);
			}
		}
		return null;
	}

	public View getPreView() {
		for (int i = 0; i < getChildCount(); i++) {
			if (getChildAt(i).getId() == (mDataIndex - 1)) {
				return getChildAt(i);
			}
		}
		return null;
	}

	public View getNextView() {
		for (int i = 0; i < getChildCount(); i++) {
			if (getChildAt(i).getId() == (mDataIndex + 1)) {
				return getChildAt(i);
			}
		}
		return null;
	}
	
	/*
	public void switchToPage(int direction) {
		switch (direction) {
		case FLIP_DIRECTION_PRE:
			snapToScreen(mDataIndex - 1);
			break;
		case FLIP_DIRECTION_NEXT:
			snapToScreen(mDataIndex + 1);
			break;
		default:
			break;
		}
	}

	public void stopFlipPage(int direction) {
		switch (direction) {
		case FLIP_DIRECTION_PRE:
			isFlipPre = false;
			break;
		case FLIP_DIRECTION_NEXT:
			isFlipNext = false;
			break;
		default:
			break;
		}
	}

	public void startFlipPage(int direction) {
		switch (direction) {
		case FLIP_DIRECTION_PRE:
			isFlipPre = true;
			break;
		case FLIP_DIRECTION_NEXT:
			isFlipNext = true;
			break;
		default:
			break;
		}
	}
	*/
}